package com.example.i2v.service;

import com.example.i2v.model.TaskQueryResponse;
import com.example.i2v.model.VideoGenerationRequest;
import com.example.i2v.model.VideoGenerationResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 视频生成服务类
 */
@Slf4j
@Service
public class VideoGenerationService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${dashscope.api.key}")
    private String apiKey;

    @Value("${dashscope.api.base-url:https://dashscope.aliyuncs.com}")
    private String baseUrl;

    /**
     * 创建视频生成任务
     */
    private VideoGenerationResponse createVideoGenerationTask(VideoGenerationRequest request) {
        log.info("开始创建视频生成任务，model：{},prompt: {}", request.getModel(),request.getInput().getPrompt());
        
        String url = baseUrl + "/api/v1/services/aigc/video-generation/video-synthesis";
        
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + apiKey);
        headers.set("Content-Type", "application/json");
        headers.set("X-DashScope-Async", "enable");
        
        HttpEntity<VideoGenerationRequest> entity = new HttpEntity<>(request, headers);
        try {
            ResponseEntity<VideoGenerationResponse> response = restTemplate.exchange(
                url, HttpMethod.POST, entity, VideoGenerationResponse.class);
            
            VideoGenerationResponse result = response.getBody();

            if (result != null && result.getOutput() != null) {
                log.info("视频生成任务创建成功，任务ID: {}", result.getOutput().getTaskId());
            } else {
                log.error("视频生成任务创建失败: {}", result != null ? result.getMessage() : "未知错误");
            }
            
            return result;
        } catch (Exception e) {
            log.error("调用视频生成API失败", e);
            throw new RuntimeException("调用视频生成API失败: " + e.getMessage(), e);
        }
    }

    /**
     * 查询任务状态
     */
    private TaskQueryResponse queryTaskStatus(String taskId) {
        log.info("查询任务状态，任务ID: {}", taskId);
        
        String url = baseUrl + "/api/v1/tasks/" + taskId;
        
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + apiKey);
        
        HttpEntity<?> entity = new HttpEntity<>(headers);
        
        try {
            ResponseEntity<TaskQueryResponse> response = restTemplate.exchange(
                url, HttpMethod.GET, entity, TaskQueryResponse.class);
            
            TaskQueryResponse result = response.getBody();
            if (result != null && result.getOutput() != null) {
                log.info("任务状态查询成功，状态: {}", result.getOutput().getTaskStatus());
            }
            
            return result;
        } catch (Exception e) {
            log.error("查询任务状态失败", e);
            throw new RuntimeException("查询任务状态失败: " + e.getMessage(), e);
        }
    }

    /**
     * 创建任务并等待完成
     */
    public TaskQueryResponse createTaskAndWait(VideoGenerationRequest request) {
        // 1. 创建任务
        VideoGenerationResponse createResponse = createVideoGenerationTask(request);
        if (createResponse.getOutput() == null || createResponse.getOutput().getTaskId() == null) {
            throw new RuntimeException("创建任务失败: " + 
                (createResponse.getMessage() != null ? createResponse.getMessage() : "未知错误"));
        }
        
        String taskId = createResponse.getOutput().getTaskId();
        log.info("任务创建成功，开始轮询任务状态，任务ID: {}", taskId);
        
        // 2. 轮询查询任务状态
        int maxAttempts = 20; // 最多查询20次
        int intervalSeconds = 15; // 每15秒查询一次
        
        for (int i = 0; i < maxAttempts; i++) {
            try {
                Thread.sleep(intervalSeconds * 1000);
                
                TaskQueryResponse queryResponse = queryTaskStatus(taskId);
                if (queryResponse.getOutput() == null) {
                    log.warn("查询任务状态返回空结果，继续等待...");
                    continue;
                }
                
                String status = queryResponse.getOutput().getTaskStatus();
                log.info("任务状态: {} (第{}次查询)", status, i + 1);
                
                if ("SUCCEEDED".equals(status)) {
                    log.info("任务执行成功！视频URL: {}", queryResponse.getOutput().getVideoUrl());
                    return queryResponse;
                } else if ("FAILED".equals(status)) {
                    throw new RuntimeException("任务执行失败");
                } else if ("CANCELED".equals(status)) {
                    throw new RuntimeException("任务已取消");
                } else if ("UNKNOWN".equals(status)) {
                    throw new RuntimeException("任务状态未知，可能已超时");
                }
                
                // 继续等待 (PENDING, RUNNING)
                
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException("等待任务完成时被中断", e);
            }
        }
        
        throw new RuntimeException("任务执行超时，请稍后手动查询任务状态");
    }
}